package android.mcsmtms.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.location.Location;
import android.mcsmtms.R;
import android.mcsmtms.R.id;
import android.mcsmtms.R.layout;
import android.mcsmtms.R.menu;
import android.mcsmtms.constant.GlobalConstants;
import android.mcsmtms.constant.GlobalConstants.Roads;
import android.mcsmtms.constant.GlobalConstants.SituationTypes;
import android.mcsmtms.constant.GlobalConstants.TrafficConditionTypes;
import android.mcsmtms.constant.GlobalConstants.UserTypes;
import android.mcsmtms.constant.GlobalProperties;
import android.mcsmtms.domain.MobileUserReport;
import android.mcsmtms.domain.User;
import android.mcsmtms.rest.RestClient;
import android.mcsmtms.util.Utilities;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.gson.Gson;

public class SendReportActivity extends Activity {
	private Spinner roadSpinner;
	private Spinner situationSpinner;
	private Spinner trafficConditionSpinner;
	private EditText descriptionText;
	private Button sendReportBtn;
	
	private SendReportTask sendReportTask;
	private User loggedUser;
	
	public static final String MOBILE_USER_REPORT_REST_SERVICE_URL = GlobalConstants.RestUrls.MOBILE_USER_REPORTS_URL;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.activity_send_report);
		
		loggedUser = Utilities.getLoggedUser(this);
		
		roadSpinner = (Spinner) findViewById(R.id.spinner_road);
		situationSpinner = (Spinner) findViewById(R.id.spinner_situation_type);
		trafficConditionSpinner = (Spinner) findViewById(R.id.spinner_traffic_condition);
		sendReportBtn = (Button) findViewById(R.id.btn_send_report);
		descriptionText = (EditText) findViewById(R.id.textarea_description);

		// Initialize Options
		int defaultSelectedRoad = -1;
		List<String> roadList = new ArrayList<String>();
		int index = 0;
		for(Roads road : Roads.values()) {
			roadList.add(road.getDescription());
			
			if(UserTypes.valueOf(loggedUser.getUserType())  == UserTypes.BAYANAN_SCOUT) {
				//roadSpinner.setSelection(position);
				if(road == Roads.BAYAN_BAYANAN) {
					defaultSelectedRoad = index;
				}
			} else if(UserTypes.valueOf(loggedUser.getUserType()) == UserTypes.EROD_SCOUT) {
				if(road == Roads.E_RODRIGUEZ) {
					defaultSelectedRoad = index;
				}
			} else if(UserTypes.valueOf(loggedUser.getUserType()) == UserTypes.JMOLINA_SCOUT) {
				if(road == Roads.J_MOLINA) {
					defaultSelectedRoad = index;
				}
				
			} else if(UserTypes.valueOf(loggedUser.getUserType()) == UserTypes.JPRIZAL_SCOUT) {
				if(road == Roads.JP_RIZAL) {
					defaultSelectedRoad = index;
				}
			} else if(UserTypes.valueOf(loggedUser.getUserType()) == UserTypes.ESANTOS_SCOUT) {
				if(road == Roads.E_SANTOS) {
					defaultSelectedRoad = index;
				}
			}
			index++;
		}
		
		List<String> situationList = new ArrayList<String>();
		for(SituationTypes situation : SituationTypes.values()) {
			situationList.add(situation.getDescription());
		}
		
		List<String> trafficList = new ArrayList<String>();
		for(TrafficConditionTypes traffic : TrafficConditionTypes.values()) {
			trafficList.add(traffic .getDescription());
		}

		ArrayAdapter<String> roadOptionsAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, roadList);
		ArrayAdapter<String> situationOptionsAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, situationList);
		ArrayAdapter<String> trafficConditionOptionsAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, trafficList);

		// Specify the layout to use when the list of choices appears
		roadOptionsAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		situationOptionsAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		trafficConditionOptionsAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// Apply the adapter to the spinner
		roadSpinner.setAdapter(roadOptionsAdapter);
		situationSpinner.setAdapter(situationOptionsAdapter);
		trafficConditionSpinner.setAdapter(trafficConditionOptionsAdapter);
		
		sendReportBtn.setOnClickListener(sendReportOnClickListener);
		if(defaultSelectedRoad > -1) {
			roadSpinner.setSelection(defaultSelectedRoad);
			roadSpinner.setEnabled(false);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.send_report, menu);
		return true;
	}
	
	private String createReportData() {
		String description = descriptionText.getText().toString();
		
		String selectedRoad = Roads.getCodeByDescription(roadSpinner.getSelectedItem().toString());
		String selectedSituation = SituationTypes.getCodeByDescription(situationSpinner.getSelectedItem().toString());
		String selectedTrafficCondition = TrafficConditionTypes.getCodeByDescription(trafficConditionSpinner.getSelectedItem().toString());
		Location currentLocation = (Location) getIntent().getExtras().get("currentLocation");

		MobileUserReport mobileUserReport = new MobileUserReport();
		
		mobileUserReport.setRoad(selectedRoad);
		mobileUserReport.setSituation(selectedSituation);
		mobileUserReport.setTrafficCondition(selectedTrafficCondition);
		mobileUserReport.setReporter(loggedUser.getId());
		mobileUserReport.setReportDateTime(new Date());
		mobileUserReport.setDescription(description);

		double latitude = (currentLocation == null) ? 0.0 : currentLocation.getLatitude();
		double longitude = (currentLocation == null) ? 0.0 : currentLocation.getLongitude(); 
		
		mobileUserReport.setLocationLat(latitude);
		mobileUserReport.setLocationLng(longitude);
		Double speed = (currentLocation != null && currentLocation.hasSpeed() ? new Double(currentLocation.getSpeed()) : 0);
		mobileUserReport.setSpeed(speed);
		
		// constructs the format of the sms report. MCDRRMO [ROAD] [SITUATION]
		// [TRAFFIC_CONDITION]
		Gson gson = new Gson();
		String mobileUserReportJson = Utilities.encodeBase64UrlSafe(gson.toJson(mobileUserReport));
		return mobileUserReportJson;
	}

	
	private View.OnClickListener sendReportOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			sendReportTask = new SendReportTask();
			sendReportTask.execute((Void) null);
		}
	};
	
	public class SendReportTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO: attempt authentication against a network service.
			
			try {
				// Simulate network access.
				//Thread.sleep(2000);
				RestClient client = new RestClient(MOBILE_USER_REPORT_REST_SERVICE_URL + "create/", loggedUser.getUserName(), loggedUser.getPassword());

				String mobileUserReportJson = createReportData();
			    client.addParam("mobileUserReport", mobileUserReportJson);
			    
			    client.execute(RestClient.RequestMethod.POST);
				
				String response = client.getResponse();
				Log.i("SendReportActivity", response);
				
			    if(response != null) {
			    	//Toast.makeText(getParent(), "GPS Enabled!", Toast.LENGTH_SHORT).show();
			    	return true;
			    } else {
			    	return false;
			    }
			} catch (Exception e) {
				Log.e("SendReportActivity", e.getLocalizedMessage());
				return false;
			}
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			sendReportTask = null;
			//showProgress(false);

			if (success) {
				Toast.makeText(SendReportActivity.this, "Report sent!", Toast.LENGTH_SHORT).show();
				Log.i("SendReportActivity", "Report sent!");
			} else {
				Toast.makeText(SendReportActivity.this, "Report not sent!", Toast.LENGTH_SHORT).show();
				Log.i("SendReportActivity", "Report not sent!");
			}
		}

		@Override
		protected void onCancelled() {
			sendReportTask = null;
			//showProgress(false);
		}
	}


}
